package com.hs.httpclient.service.impl;

import com.hs.httpclient.service.AbstractHttpRequest;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

/**
 * @Author: songhao
 * @Date: 2020/11/12
 * @Description: 发送post请求的实现类
 */
public class PostMethodRquestmpl extends AbstractHttpRequest {

    static final Logger logger = LoggerFactory.getLogger(PostMethodRquestmpl.class);

    @Override
    public String requestPostByForm(String url, Map<String, String> headerMap, Map<String, Object> paramMap) throws Exception {
        logger.info("===>正在请求url:{}",url);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try{
            HttpPost httpPost = new HttpPost(url);
            setRequestHead(httpPost, headerMap);
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.setCharset(Charset.forName("utf-8"));
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
            //填充参数
            Set<String> keySet = paramMap.keySet();
            for(String key:keySet){
                Object obj = paramMap.get(key);
                if(obj instanceof File){ //参数是File 类型
                    File file = (File) obj;
                    entityBuilder.addPart(key, new FileBody(file));
                }else if(obj instanceof String){ //参数是String 类型
                    String value = (String) obj;
                    entityBuilder.addPart(key, new StringBody(value,contentType));
                }else if(obj instanceof byte[]){
                    byte[] bytes = (byte[]) obj;
                    entityBuilder.addPart(key, new ByteArrayBody(bytes,ContentType.DEFAULT_BINARY,key));
                }else{
                    throw new IllegalArgumentException(key+"的类型是"+obj.getClass()+"（允许的参数类型为File 或者 String）。");
                }
            }

            httpPost.setEntity(entityBuilder.build());
            httpClient = HttpClientBuilder.create().build();
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                return result;
            }
        }catch (Exception e){
            throw e;
        }finally {
            try {
                if(httpClient != null){
                    httpClient.close();
                }
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
        return null;
    }
}
